package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrs;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryByCatIdPage(Map<String, Object> params, Long catId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)) {
            wrapper.and((obj) -> {
                //这里可以用lambda表达式，这样and后面的这一堆就是用括号括起来的
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        if (catId == null || catId.equals(0L)) {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );

            return new PageUtils(page);
        } else {
            wrapper.eq("catelog_id", catId);
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }
    }

    @Override
    public List<AttrEntity> getAttrsByAttrGroupId(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        ArrayList<Long> attrIds = new ArrayList<>();
        for (AttrAttrgroupRelationEntity relationEntity : relationEntities) {
            attrIds.add(relationEntity.getAttrId());
        }
        return attrDao.selectBatchIds(attrIds);
    }

    @Override
    public void relationDelete(List<AttrAttrgroupRelationEntity> relationEntities) {
        relationDao.relationDelete(relationEntities);
    }

    @Override
    public void saveAttrRelation(List<AttrAttrgroupRelationEntity> relationEntities) {

        relationService.saveBatch(relationEntities);
    }

    /*
    * 查询当前属性分组所属的分类下未被其他分组关联属性
    * */
    @Override
    public PageUtils noAttrRelation(Map<String, Object> params, Long attrgroupId) {


        //查询当前分组所属分类
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrgroupId);

        //查询当前分类下的所有分组
        List<AttrGroupEntity> attrGroupEntities = baseMapper.
                selectList(new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", attrGroupEntity.getCatelogId()));
        List<Long> attrGroupIds = attrGroupEntities.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());

        //查询上面分组关联的所有属性
        List<Long> attrIds = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds))
                .stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        //查询所属分类下的所有基本属性,并排除已被关联的属性，还需考虑搜素关键字
        QueryWrapper<AttrEntity> wrapper1 = new QueryWrapper<AttrEntity>().
                eq("catelog_id", attrGroupEntity.getCatelogId())
                .eq("attr_type", ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0){
            wrapper1.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper1.and((wrapper)->wrapper.eq("attr_id",key)).or().like("attr_name",key);
        }
        List<AttrEntity> attrEntities = attrDao.selectList(wrapper1);

        PageUtils pageUtils = new PageUtils(attrEntities, attrEntities.size(),
                Integer.parseInt((String) params.get("limit")),
                Integer.parseInt((String) params.get("page")));

        return pageUtils;
    }

    @Override
    public List<AttrGroupWithAttrs> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        List<AttrGroupEntity> attrGroupEntities = this.baseMapper.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<AttrGroupWithAttrs> collect = attrGroupEntities.stream().map(item -> {
            AttrGroupWithAttrs attrGroupWithAttrs = new AttrGroupWithAttrs();
            BeanUtils.copyProperties(item,attrGroupWithAttrs);
            List<AttrEntity> attrEntities = this.getAttrsByAttrGroupId(item.getAttrGroupId());
            attrGroupWithAttrs.setAttrs(attrEntities);
            return attrGroupWithAttrs;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<SkuItemVo.SpuItemAttrGroupVo> getAttrWithGroupNameBySpuId(Long spuId) {
        return baseMapper.getAttrWithGroupNameBySpuId(spuId);
    }
}